package net.starwifi.duobao.service.impl;

import net.starwifi.duobao.SettingUtils;
import net.starwifi.duobao.entity.DBShareImage;
import net.starwifi.duobao.plugin.StoragePlugin;
import net.starwifi.duobao.service.BaseServiceImpl;
import net.starwifi.duobao.service.DBShareImageService;
import net.starwifi.duobao.utils.ImageUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.*;

/**
 * Created by Administrator on 2015/11/19.
 */
@Service
public class DBShareImageServiceImpl extends BaseServiceImpl<DBShareImage,Long> implements DBShareImageService {

    /** 目标扩展名 */
    private static final String DEST_EXTENSION = "jpg";
    /** 目标文件类型 */
    private static final String DEST_CONTENT_TYPE = "image/jpeg";

    /** servletContext */
    private ServletContext servletContext;

    @Resource(name = "taskExecutor")
    private TaskExecutor taskExecutor;
    @Resource
    private List<StoragePlugin> storagePlugins;

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * 添加图片处理任务 图片文件(缩略)上传路径
     * @param tempFile 原临时文件
     * @param contentType  原文件类型
     */
    private void addTask(final String sourcePath, final String largePath, final String mediumPath, final String thumbnailPath, final File tempFile, final String contentType) {
        try {
            taskExecutor.execute(new Runnable() {
                public void run() {
                    Collections.sort(storagePlugins);
                    for (StoragePlugin storagePlugin : storagePlugins) {
                        if (storagePlugin.getIsEnabled()) {
                            String tempPath = System.getProperty("java.io.tmpdir");
//                            File watermarkFile = new File(servletContext.getRealPath(SettingUtils.get("productWatermarkPath")));
                            File largeTempFile = new File(tempPath + "/upload_" + UUID.randomUUID() + "." + DEST_EXTENSION);
                            File mediumTempFile = new File(tempPath + "/upload_" + UUID.randomUUID() + "." + DEST_EXTENSION);
                            File thumbnailTempFile = new File(tempPath + "/upload_" + UUID.randomUUID() + "." + DEST_EXTENSION);
                            try {
                                ImageUtils.zoom(tempFile, largeTempFile, Integer.parseInt(SettingUtils.get("productLargeWidth")), Integer.parseInt(SettingUtils.get("productLargeHeight")));
                                //ImageUtils.addWatermark(largeTempFile, largeTempFile, watermarkFile, Integer.parseInt(SettingUtils.get("productWatermarkPos")), Integer.parseInt(SettingUtils.get("productWatermarkAlpha")));
                                ImageUtils.zoom(tempFile, mediumTempFile, Integer.parseInt(SettingUtils.get("productMediumWidth")),Integer.parseInt(SettingUtils.get("productMediumHeight")));
                                //ImageUtils.addWatermark(mediumTempFile, mediumTempFile, watermarkFile, Integer.parseInt(SettingUtils.get("productWatermarkPos")), Integer.parseInt(SettingUtils.get("productWatermarkAlpha")));
                                ImageUtils.zoom(tempFile, thumbnailTempFile,  Integer.parseInt(SettingUtils.get("productThumbWidth")),Integer.parseInt(SettingUtils.get("productThumbHeight")));
                                storagePlugin.upload(sourcePath, tempFile, contentType);
                                storagePlugin.upload(largePath, largeTempFile, DEST_CONTENT_TYPE);
                                storagePlugin.upload(mediumPath, mediumTempFile, DEST_CONTENT_TYPE);
                                storagePlugin.upload(thumbnailPath, thumbnailTempFile, DEST_CONTENT_TYPE);
                            } finally {
                                FileUtils.deleteQuietly(tempFile);
                                FileUtils.deleteQuietly(largeTempFile);
                                FileUtils.deleteQuietly(mediumTempFile);
                                FileUtils.deleteQuietly(thumbnailTempFile);
                            }
                            break;
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void build(DBShareImage productImage,String path) {
        MultipartFile multipartFile = productImage.getFile();
        if (multipartFile != null && !multipartFile.isEmpty()) {
            try {
                Map<String, Object> model = new HashMap<String, Object>();
                model.put("uuid", UUID.randomUUID().toString());
                String uuid = UUID.randomUUID().toString();
                String sourcePath = path + uuid + "-source." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
                String largePath = path + uuid + "-large." + DEST_EXTENSION;
                String mediumPath = path + uuid + "-medium." + DEST_EXTENSION;
                String thumbnailPath = path + uuid + "-thumbnail." + DEST_EXTENSION;
                Collections.sort(storagePlugins);
                for (StoragePlugin storagePlugin : storagePlugins) {
                    if (storagePlugin.getIsEnabled()) {
                        File tempFile = new File(System.getProperty("java.io.tmpdir") + "/upload_" + UUID.randomUUID() + ".tmp");
                        if (!tempFile.getParentFile().exists()) {
                            tempFile.getParentFile().mkdirs();
                        }
                        multipartFile.transferTo(tempFile);
                        addTask(sourcePath, largePath, mediumPath, thumbnailPath, tempFile, multipartFile.getContentType());
                        productImage.setSource(storagePlugin.getUrl(sourcePath));
                        productImage.setLarge(storagePlugin.getUrl(largePath));
                        productImage.setMedium(storagePlugin.getUrl(mediumPath));
                        productImage.setThumbnail(storagePlugin.getUrl(thumbnailPath));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
